<?php

namespace app\manage\controller;


use app\common\validate\merchant\MerchantRolesValid;
use app\manage\loader\ManageServices;
use think\Exception;

/**
 * 系统角色
 */
class SystemRole extends BaseApi
{

    /**
     * 角色组分页
     */
    public function role_page()
    {
        $params = $this->request->get();
        try {
            $option = $this->formatOption($params);
            $where = [];
            if (!empty($option['keyword'])) {
                $where[] = ['title', 'like', '%' . $option['keyword'] . '%'];
            }
            $option['where'] = $where;
            $result = ManageServices::SystemRole()->getPage($option);
            api_result(API_SUCCESS, "请求成功", $result);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 角色列表
     */
    public function role_list()
    {
        $params = $this->request->get();
        try {
            $allField = $params['flag'] ?? 0;
            $params['limit'] = $params['limit'] ?? 30;
            $option = $this->formatOption($params);
            $where = [];
            if (!empty($option['keyword'])) {
                $where[] = ['title', 'like', '%' . $option['keyword'] . '%'];
            }
            $option['where'] = $where;

            $result = ManageServices::SystemRole()->getList($option, $allField);
            api_result(API_SUCCESS, "请求成功", $result);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     *  角色组添加/修改
     */
    public function role_save()
    {
        $params = $this->request->post();
        try {
            $params['op_user'] = $this->opUser;
            $params['is_sys'] = 0;
            $scene = '.create';
            if (!empty($params['id'])) {
                unset($params['op_user']);
                $scene = '.edit';
            }
            $this->validate($params, MerchantRolesValid::class . $scene);
            ManageServices::SystemRole()->roleSave($params);
            api_result(API_SUCCESS, "保存成功");
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 角色信息
     */
    public function role_info()
    {
        try {
            $param = $this->request->get();
            validate(MerchantRolesValid::class)->scene('Info')->check($param);
            $info = ManageServices::SystemRole()->roleInfo($param['id']);
            api_result($info);
        } catch (Exception $e) {
            api_result($e);
        }
    }


    /**
     * 删除组角色
     * @title 删除角色
     * @auth true
     */
    public function role_del()
    {
        try {
            $id = $this->request->post('id');
            if (empty($id)) {
                api_exception(400, '角色ID不能为空');
            }
            ManageServices::SystemRole()->roleDel($id);
            api_result(API_SUCCESS, "删除成功");
        } catch (Exception $e) {
            api_result($e);
        }
    }

}
